#!/usr/bin/env python3
"""
远程服务器启动和验证脚本
用法: python remote_startup_and_verify.py
"""

import os
import sys
import subprocess
import time
import requests
import json
from pathlib import Path
from datetime import datetime

# 颜色定义
class Colors:
    HEADER = '\033[95m'
    BLUE = '\033[94m'
    CYAN = '\033[96m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def print_header(text):
    """打印标题"""
    print(f"\n{Colors.BLUE}{'='*60}{Colors.ENDC}")
    print(f"{Colors.BLUE}{text}{Colors.ENDC}")
    print(f"{Colors.BLUE}{'='*60}{Colors.ENDC}\n")

def print_success(text):
    """打印成功信息"""
    print(f"{Colors.GREEN}✅ {text}{Colors.ENDC}")

def print_error(text):
    """打印错误信息"""
    print(f"{Colors.RED}❌ {text}{Colors.ENDC}")

def print_warning(text):
    """打印警告信息"""
    print(f"{Colors.YELLOW}⚠️  {text}{Colors.ENDC}")

def print_info(text):
    """打印信息"""
    print(f"{Colors.CYAN}ℹ️  {text}{Colors.ENDC}")

def verify_code():
    """验证代码"""
    print_header("1️⃣  代码验证")

    results = []

    # 检查接口
    with open('src/main.py', 'r') as f:
        if 'process-video-text-only' in f.read():
            print_success("/process-video-text-only 接口已添加")
            results.append(True)
        else:
            print_error("/process-video-text-only 接口未找到")
            results.append(False)

    # 检查方法
    with open('src/video_processor.py', 'r') as f:
        if 'process_video_text_only' in f.read():
            print_success("process_video_text_only() 方法已添加")
            results.append(True)
        else:
            print_error("process_video_text_only() 方法未找到")
            results.append(False)

    return all(results)

def verify_syntax():
    """验证 Python 语法"""
    print_header("2️⃣  Python 语法验证")

    files = ['src/main.py', 'src/video_processor.py']
    results = []

    for filepath in files:
        try:
            with open(filepath, 'r') as f:
                compile(f.read(), filepath, 'exec')
            print_success(f"{filepath} 语法正确")
            results.append(True)
        except SyntaxError as e:
            print_error(f"{filepath} 语法错误: {e}")
            results.append(False)

    return all(results)

def verify_dependencies():
    """验证依赖"""
    print_header("3️⃣  依赖验证")
    
    packages = ['fastapi', 'starlette', 'cv2', 'numpy', 'paddle']
    results = []
    
    for package in packages:
        try:
            __import__(package)
            print_success(f"{package} 已安装")
            results.append(True)
        except ImportError:
            print_warning(f"{package} 未安装")
            results.append(False)
    
    return all(results)

def start_service():
    """启动服务"""
    print_header("4️⃣  启动 FastAPI 服务")
    
    print_info("启动服务在 http://localhost:8000")
    print_info("按 Ctrl+C 停止服务")
    print_info("")
    
    try:
        # 启动服务
        process = subprocess.Popen(
            ['python', '-m', 'uvicorn', 'src.main:app', '--host', '0.0.0.0', '--port', '8000'],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        print_success(f"服务已启动 (PID: {process.pid})")
        
        # 等待服务启动
        print_info("等待服务启动...")
        time.sleep(3)
        
        # 检查进程是否仍在运行
        if process.poll() is None:
            print_success("服务进程正在运行")
            return process
        else:
            print_error("服务启动失败")
            stdout, stderr = process.communicate()
            print_error(f"错误输出: {stderr}")
            return None
    except Exception as e:
        print_error(f"启动服务失败: {e}")
        return None

def test_health_check(max_retries=5):
    """测试健康检查"""
    print_header("5️⃣  API 测试")
    
    print_info("测试健康检查...")
    
    for attempt in range(max_retries):
        try:
            response = requests.get('http://localhost:8000/health', timeout=2)
            if response.status_code == 200:
                print_success("健康检查通过")
                data = response.json()
                print(f"  响应: {json.dumps(data, indent=2)}")
                return True
            else:
                print_warning(f"健康检查返回状态码: {response.status_code}")
        except requests.exceptions.ConnectionError:
            if attempt < max_retries - 1:
                print_warning(f"连接失败，重试 ({attempt + 1}/{max_retries})...")
                time.sleep(1)
            else:
                print_error("无法连接到服务")
                return False
        except Exception as e:
            print_error(f"测试失败: {e}")
            return False
    
    return False

def display_service_info():
    """显示服务信息"""
    print_header("6️⃣  服务信息")
    
    print_info("服务 URL: http://localhost:8000")
    print_info("API 文档: http://localhost:8000/docs")
    print_info("ReDoc: http://localhost:8000/redoc")

def display_endpoints():
    """显示可用的 API 端点"""
    print_header("7️⃣  可用的 API 端点")
    
    endpoints = [
        ("GET", "/health", "健康检查"),
        ("POST", "/process-video", "处理视频（完整结果）"),
        ("POST", "/process-video-with-output", "处理视频（输出视频）"),
        ("POST", "/process-video-text-only", "处理视频（仅文本）"),
    ]
    
    for method, path, description in endpoints:
        print(f"  {method:6} {path:30} - {description}")

def display_test_commands():
    """显示测试命令"""
    print_header("8️⃣  测试命令")
    
    print("\n基础测试:")
    print("  curl -X GET 'http://localhost:8000/health'")
    
    print("\n文本识别接口测试:")
    print("  curl -X POST 'http://localhost:8000/process-video-text-only' \\")
    print("    -F 'file=@test.mp4'")
    
    print("\n带参数的测试:")
    print("  curl -X POST 'http://localhost:8000/process-video-text-only' \\")
    print("    -F 'file=@test.mp4' \\")
    print("    -F 'sample_rate=5' \\")
    print("    -F 'min_score=0.8'")
    
    print("\n在另一个终端中测试:")
    print("  ssh asr@192.168.10.11")
    print("  curl -X GET 'http://localhost:8000/health'")

def display_next_steps():
    """显示下一步"""
    print_header("📞 下一步")
    
    print("\n1. 在另一个终端中测试接口:")
    print("   ssh asr@192.168.10.11")
    print("   curl -X GET 'http://localhost:8000/health'")
    
    print("\n2. 查看 API 文档:")
    print("   访问 http://192.168.10.11:8000/docs")
    
    print("\n3. 查看详细文档:")
    print("   cat REMOTE_TEST_GUIDE.md")
    
    print("\n4. 停止服务:")
    print("   按 Ctrl+C")

def main():
    """主函数"""
    print(f"\n{Colors.BOLD}{Colors.BLUE}╔════════════════════════════════════════════════════════════╗{Colors.ENDC}")
    print(f"{Colors.BOLD}{Colors.BLUE}║{Colors.ENDC}  远程服务器启动和验证")
    print(f"{Colors.BOLD}{Colors.BLUE}║{Colors.ENDC}  启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"{Colors.BOLD}{Colors.BLUE}╚════════════════════════════════════════════════════════════╝{Colors.ENDC}")
    
    # 检查是否在项目目录中
    if not os.path.exists('src/main.py'):
        print_error("未找到 src/main.py，请在项目根目录中运行此脚本")
        sys.exit(1)
    
    print_info(f"项目路径: {os.getcwd()}")
    
    # 执行验证
    try:
        # 代码验证
        if not verify_code():
            print_error("代码验证失败")
            sys.exit(1)
        
        # 语法验证
        if not verify_syntax():
            print_error("语法验证失败")
            sys.exit(1)
        
        # 依赖验证
        verify_dependencies()
        
        # 启动服务
        process = start_service()
        if process is None:
            sys.exit(1)
        
        # 测试健康检查
        if not test_health_check():
            print_error("健康检查失败")
            process.terminate()
            sys.exit(1)
        
        # 显示信息
        display_service_info()
        display_endpoints()
        display_test_commands()
        display_next_steps()
        
        # 完成
        print_header("✅ 验证完成")
        print("\n服务已启动并通过验证！")
        print("服务将继续运行，按 Ctrl+C 停止\n")
        
        # 等待用户中断
        process.wait()
        
    except KeyboardInterrupt:
        print("\n\n服务已停止")
        sys.exit(0)
    except Exception as e:
        print_error(f"发生错误: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()

